-module(parser).

-export([splite_message/1]).

-include("megaeyes.hrl").

splite_request(Bin,Header) ->
    Len = Header#message.len,
    <<Srcid:32/binary,Dstid:32/binary,Req:Len/binary,Rest/binary>> = Bin,		
    Request =  Header#message{srcid=Srcid,dstid=Dstid,body=Req},
    {ok,all,Request,Rest}.

splite_response(Bin,Header) ->
    Len = Header#message.len,
    <<Success:32/little,Resp:Len/binary,Rest/binary>> = Bin,		
    Response = Header#message{success=Success,body=Resp},
    {ok,all,Response,Rest}.

splite_message(Msg) ->
    %Bin = list_to_binary(Msg)%
    MsgLen = binlistsize(Msg),
    try
	if 
	    MsgLen > ?SOCKHEADLENGTH ->
		<<Ver:32/little,Len:32/little,Id:32/little,No:32/little,Other/binary>> = list_to_binary(Msg),
		Header = #message{ver=Ver,len=Len,id=Id,no=No},
		case Id rem 2 of
		    0 ->
			splite_request(Other,Header);
		    1 ->
			splite_response(Other,Header)
		end;
	    true ->
		{error,shortmsg}
	end
    catch
	_:Why ->
	    {error,Why}
    end.

binlistsize_c([],Len) ->
    Len;
binlistsize_c([H|Rest],Len) ->
    binlistsize_c(Rest,Len+byte_size(H)).

binlistsize(BinList) ->
    binlistsize_c(BinList,0).
